import urllib.request as ur
import urllib.parse as up
import json
import user_agent

# 构造网页Request请求
def getResquest(url,data):
    request = ur.Request(
        url=url,
        data=data,
        headers={
            'Use-Agent':user_agent.get_user_agent_pc(),
        }
    )
    response = ur.urlopen(request).read()
    return response

if __name__ == '__main__':
    try:
        while True:
            # 获取待翻译的文本并储存为字典类型
            context = input('请输入你需要翻译的中文：')
            data = {
                'kw':context
            }
            # 对data进行url编码
            data_url = up.urlencode(data).encode('utf-8')
            # 构造request对象并添加访问的数据
            response = getResquest(
                url='https://fanyi.baidu.com/sug',
                data=data_url,
            )
            # 将json对象转换为python字典
            ret = json.loads(response)
            # 得到返回的结果
            translate_s = ret['data']
            # 如果有多个结果，多次打印
            for translate in translate_s:
                translate = translate['v']
                print('翻译的结果为：',translate)
    except Exception as e:
        print(e)